package com.codez.unionpay.netty;

import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 *  @author codez
 *	@createTime 2019-05-18 04:58:26
 */

public class NettyClientHandler  extends ChannelInboundHandlerAdapter{

	Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
	
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
		ByteBuf in = (ByteBuf) msg;
		Scanner scanner = new Scanner(System.in);
//		logger.info(" from server > " + in.toString(Charsets.UTF_8));
//		logger.info(" response client > ");
		System.out.println(" from server > " + in.toString(Charsets.UTF_8));
		System.out.print(" response server > ");
		
		String m = scanner.nextLine();
		
		ChannelFuture future = ctx.writeAndFlush(Unpooled.copiedBuffer(m , Charsets.UTF_8));

		if("exit".equalsIgnoreCase(m)){
			logger.info(" 客户端请求关闭连接 ");
			future.addListeners(ChannelFutureListener.CLOSE);//
		}
		
	}

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello server", CharsetUtil.UTF_8));
    }

}
